package com.yao2san.sim.storage.client.core.downloader;

import com.yao2san.sim.storage.client.util.StorageUtil;
import com.yao2san.sim.storage.client.config.LocalProperties;
import com.yao2san.sim.storage.client.config.MinioProperties;
import com.yao2san.sim.storage.client.config.SimStorageClientProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
public class LocalDownloader extends AbstractDownloader {

    private final LocalProperties localProperties;

    private final static String SEPARATOR = "/";


    public LocalDownloader(LocalProperties localProperties) {
        this.localProperties = localProperties;
    }

    @Override
    public void download(String object, OutputStream out) {
        StorageUtil.checkObjectName(object);
        String pathName = getPathName(object);
        try (InputStream input = Files.newInputStream(Paths.get(pathName))) {
            IOUtils.copy(input, out);
        } catch (IOException e) {
            log.error("file download error", e);
            throw new RuntimeException(e);
        }
    }

    private String getPathName(String object) {
        return StorageUtil.formatPath(this.localProperties.getBucket() + "/" + object);
    }

    @Override
    public String url(String object) {
        return url(object, false);
    }

    @Override
    public String url(String object, boolean preSigned) {
        if (preSigned) {
            throw new IllegalArgumentException("Local storage not support pre-signed yet, please set preSigned false");

        } else {
            return localProperties.getEndpoint() + StorageUtil.formatPath(SEPARATOR + localProperties.getPrefix() + SEPARATOR + object);
        }
    }

    @Override
    public String getName() {
        return StorageType.LOCAL.name();
    }
}
